/*
 * Copyright 2011 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fr.gaellalire.jzip.view;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.util.EventObject;

import javax.swing.AbstractCellEditor;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

/**
 *
 * @author Gael Lalire
 */
public class NameTableCellRenderer extends AbstractCellEditor implements TableCellRenderer, TableCellEditor {

    private static final long serialVersionUID = 1927722287888776010L;

    private JPanel panel;

    private JPanel editPanel;

    public NameTableCellRenderer() {
        panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
        panel.setOpaque(false);
        editPanel = new JPanel();
        editPanel.setLayout(new BorderLayout());
    }

    @Override
    public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
        JLabel label = (JLabel) value;
        label.setOpaque(true);
        if (isSelected) {
            label.setBackground(table.getSelectionBackground());
            label.setForeground(table.getSelectionForeground());
        } else {
            label.setBackground(table.getBackground());
            label.setForeground(table.getForeground());
        }
        panel.removeAll();
        panel.add(label);
        return panel;
    }

    @Override
    public boolean isCellEditable(final EventObject e) {
        return false;
    }

    private JTextField jTextField = new JTextField();

    private JLabel editingLabel;

    @Override
    public Object getCellEditorValue() {
        editingLabel.setText(jTextField.getText());
        return editingLabel;
    }

    @Override
    public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column) {
        editPanel.removeAll();
        editingLabel = (JLabel) value;
        editPanel.add(new JLabel(editingLabel.getIcon()), BorderLayout.WEST);
        jTextField.setText(editingLabel.getText());
        editPanel.add(jTextField, BorderLayout.CENTER);
        return editPanel;
    }

}
